<template>
  <div>
    <el-dialog
      :title="isEdit ? '修改' : title"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="俱乐部类型">
          <el-select
            v-model="form.clubType"
            placeholder="请选择"
            :disabled="isEdit"
          >
            <el-option
              v-for="item in dict.CLUB_TYPE"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主题">
          <el-input v-model="form.theme" clearable></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <div style="border: 1px solid #ccc;" class="editor">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 400px; overflow-y: hidden;"
              v-model="form.content"
              @input="handleInput"
              :defaultConfig="editorConfig"
              :defaultContent="defaultContent"
              :mode="mode"
              @onCreated="onCreated"
              @onChange="onChange"
              @onMaxLength="onMaxLength"
            />
          </div>
        </el-form-item>
        <el-form-item label="报名截止时间">
          <el-date-picker
            v-model="form.deadline"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import club from "@/api/club/index";
import { getToken } from "@/utils/auth";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { DomEditor } from "@wangeditor/editor";
import "@wangeditor/editor/dist/css/style.css";
import { Loading } from "element-ui";
export default {
  name: "ClubDialog",
  components: {
    Editor,
    Toolbar
  },
  props: {
    title: {
      type: String,
      default: "新增"
    }
  },
  dicts: ["CLUB_TYPE"],
  data() {
    return {
      dialogVisible: false,
      isEdit: false, //是否编辑
      form: {
        id: "",
        clubType: "0", //俱乐部类型
        theme: "",
        content: "", //描述
        deadline: "" //报名截止时间
      },
      editor: null,
      mode: "default", // or 'simple'
      toolbarConfig: {
        // 排除工具栏配置
        excludeKeys: [
          // 全屏，网络视频，本地视频，表情，代码，待办，代码块，插入图片
          "fullScreen",
          "uploadVideo",
          "group-video",
          "emotion",
          "code",
          "todo",
          "codeBlock",
          "insertImage"
        ],
        insertKeys: {
          keys: ['ParagraphSpacingBefore', 'ParagraphSpacingAfter'],
          index: 10,
        },
      },
      editorConfig: {
        placeholder: "请输入内容...",
        maxLength: this.maxLength, // 限制富文本输入文本字数
        MENU_CONF: {
          uploadImage: {
            // 最多可上传几个文件，默认为 100
            // maxNumberOfFiles: 10,
            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 1 * 1024 * 1024 * 50, // 1M
            // 小于该值就插入 base64 格式（而不上传），默认为 0
            base64LimitSize: 5 * 1024, // 5kb
            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制
            allowedFileTypes: ["image/*"],
            // 图片上传
            async customUpload(file, insertFn) {
              const formData = new FormData();
              formData.append("file", file);
              let loading = Loading.service({
                fullscreen: true,
                lock: true,
                text: "正在加载，请耐心等待...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
              });
              club
                .upFile(formData)
                .then(res => {
                  loading.close();
                  insertFn(res.url, "image");
                })
                .catch(() => {
                  loading.close();
                });

              // const res = await uploadF(formData)
              // if (res.data) {
              //     insertFn(`图片地址`, 'image')
              // } else {
              //     this.$message.error('图片上传失败，请重新上传!');
              // }
            }
          },
          fontFamily: {
            fontFamilyList: [
              { name: "仿宋", value: "fangsong" },
              { name: "黑体", value: "Arial" },
              { name: "宋体", value: "SimSun" },
              { name: "楷书", value: "KaiTi" },
              { name: "隶书", value: "LiSu" }
            ]
          },
          lineHeight: {
            lineHeightList: ["1", "1.5", "1.75", "2", "2.5"]
          }
        }
      },
      defaultContent: [
        {
          type: "paragraph",
          lineHeight: "1.75",
          children: [
            {
              fontSize: "16px",
              lineHeight: "1.75",
              color: "rgba(0, 0, 0, 0.85)",
              text: ""
            }
          ]
        }
      ]
    };
  },
  computed: {
    uploadUrl() {
      return process.env.VUE_APP_BASE_API + "/public/file/upload";
    },
    headers() {
      return { Authorization: getToken() };
    }
  },

  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
      this.$nextTick(() => {
        const toolbar = DomEditor.getToolbar(this.editor);
        this.curToolbarConfig = toolbar.getConfig();
      });
    },
    handleInput(value) {
      this.$emit("change", value); // 将内容同步到父组件中
    },
    onChange(editor) {
      // 监听富文本输入
      const text = editor.getText().replace(/\n|\r/gm, "");
      this.textLength = text.length;
    },
    onMaxLength(editor) {
      // 当输入值达到限制值时触发事件
      this.$message.warning("输入文本数已到达最大值！");
    },
    submitHandle() {
      if (this.isEdit) {
        //修改
        club
          .clubEdit(this.form)
          .then(res => {
            this.dialogVisible = false;
            this.$notify({ message: "操作成功", type: "success" });
            this.$emit("submitSuccess");
          })
          .catch(() => {});
      } else {
        club
          .clubAdd(this.form)
          .then(res => {
            this.dialogVisible = false;
            this.$notify({ message: "操作成功", type: "success" });
            this.$emit("submitSuccess");
          })
          .catch(() => {});
      }
    }
  }
};
</script>

<style lang="scss"></style>
